/*
 * Copyright 2022-2023 the original author(https://github.com/wj596)
 * 
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */

package org.jsets.fastboot.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jsets.fastboot.security.SecurityContext;
import org.jsets.fastboot.security.SecurityUtils;
import org.jsets.fastboot.security.authc.IAuthcExceptionHandler;
import org.jsets.fastboot.util.StringUtils;
import org.jsets.fastboot.util.WebUtils;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.filter.OncePerRequestFilter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TokenAuthcFilter extends OncePerRequestFilter {

	protected final IAuthcExceptionHandler exceptionHandler;

	public TokenAuthcFilter(IAuthcExceptionHandler exceptionHandler) {
		this.exceptionHandler = exceptionHandler;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
		SecurityContext.cleanup();
		boolean doContinue = false;
		String servletPath = request.getServletPath();
		if (SecurityUtils.isIgnoringPath(servletPath)) {
			log.info("地址[{}]忽略认证", servletPath);
			doContinue = true;
		} else {
			try {
				String token = WebUtils.getAuthorization(request);
				if (StringUtils.isBlank(token)) {
					throw new InsufficientAuthenticationException(SecurityUtils.getProperties().getTokenBlankTips());
				}
				
				SecurityUtils.getAuthenticator().authenticate(token);
				doContinue = true;
				log.info("地址[{}]认证成功", servletPath);
			} catch (AuthenticationException e) {
				log.info("地址[{}]认证失败[{}]", servletPath, e.getMessage());
				this.exceptionHandler.handle(request, response, e);
			}
		}

		if (doContinue) {
			chain.doFilter(request, response);
		}
	}

}